package cn.fu.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.fu.service.CoreService;
import cn.fu.service.TokenValidate;
import cn.fu.util.CheckUtil;
import cn.fu.util.Const;
import cn.fu.util.Conversion;
import cn.fu.util.MessageUtil;
import cn.fu.util.WeixinUtil;

/**
 * 
 * @ClassName: WeiXinController
 * @Description: Token校验
 * @author zhangxiaofu
 * @date 2016年5月15日 上午11:01:03
 *
 */
@Controller
public class WeiXinController {
	private Logger log = Logger.getLogger(WeiXinController.class);

	/**
	 * 修改配制：服务器配置，微信进行服务器Token校验 校验信息是否是从微信服务器发过来的
	 * 
	 * @param req
	 * @param resp
	 * @throws Exception
	 */
	@RequestMapping(value = "wx", method = { RequestMethod.GET }, produces = "application/json;charset=UTF-8")
	public void validate(TokenValidate weChat, PrintWriter out) throws Exception {
		System.err.println("get");
		String signature = weChat.getSignature(); // 微信加密签名
		String timestamp = weChat.getTimestamp(); // 时间戳
		String nonce = weChat.getNonce();// 随机数
		String echostr = weChat.getEchostr();// 随机字符串

		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		} else {
			System.out.println("打印日志：失败或非微信官方接收");
		}
		out.flush();
		out.close();
	}

	/**
	 * 
	 * @Title: validateToken @Description: 文本消息的接收与响应 ：微信消息的处理 @param @param
	 *         req @param @param resp @param @throws IOException 设定文件 @return
	 *         void 返回类型 @throws
	 */
	@RequestMapping(value = "wx", method = { RequestMethod.POST }, produces = "application/xml;charset=UTF-8")
	public void messageDispose(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		PrintWriter out = resp.getWriter();

		try {
			// 调用CoreService类的processRequest方法接收、处理消息，并得到处理结果；机器人自动回复或者自定义消息
			String respMessage = CoreService.processRequest(req);

			// 响应消息
			// 调用response.getWriter().write()方法将消息的处理结果返回给用户
			out.print(respMessage);
		}  catch (Exception e) {
			e.printStackTrace();
		}finally{
			out.close();
		}
	}
}
